<?php

namespace yunj\init\step;

use think\facade\Db;

/**
 * Demo数据初始化
 * Class DemoDataInit
 * @package yunj\init\step
 */
class DemoDataInit extends Step {

    public function handle() {
        $prefix = $this->getDbConnConfig('prefix');
        // 数据表是否存在
        $exist = false;
        $tables = ['yunj_demo_interest_cate', 'yunj_demo_user'];
        foreach ($tables as $table) {
            $_exist = Db::query("show tables like '{$prefix}{$table}'");
            if ($_exist) {
                $exist = true;
                break;
            }
        }
        if ($exist) {
            $tableStr = implode('、', $tables);
            $res = $this->confirm("Demo数据[{$tableStr}]已存在，是否覆盖为当前版本最新数据，确认继续执行？否 将跳过 {$this->desc} 流程");
            if (!$res) {
                return self::RES_SKIP;
            }
            $this->info("覆盖中...");
        }
        $demoSql = parse_sql_file(
            ds_replace(YUNJ_VENDOR_SRC_PATH . 'init/sql/demo.sql'),
            true,
            ['__PREFIX__','__CHARSET__'],
            [$prefix, $this->getDbCharset()],
        );
        Db::transaction(function () use ($demoSql) {
            foreach ($demoSql as $itemSql) {
                Db::execute($itemSql);
            }
        });
        return self::RES_SUCCESS;
    }

}